package colony;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeMap;

public class Agrupamento {

	public static int count_class = 0;

	public static TreeMap<Integer, Integer> classes = new TreeMap<Integer, Integer>();

	public static List<List<Integer>> agrupamentos = new ArrayList<List<Integer>>();

	public static void update(int itemId, int classe) {
		classes.put(itemId, classe);
	}

	public static void updateBasedItem(int itemId, int referenceItemId) {
		Integer id = classes.get(referenceItemId);		
		if(id == null){
			System.out.println("updateBased");
			System.out.println(itemId+" "+referenceItemId);
			System.exit(0);
		}
		classes.put(itemId, classes.get(referenceItemId));
	}

	public static int getNewClass() {
		return count_class++;
	}

	public static void print() {
		System.out.println("***PRINT");
		NavigableSet<Integer> keys = classes.navigableKeySet();
		for (Integer k : keys) {
			System.out.println("id: " + k + "\tclass: " + classes.get(k));
		}
		//System.out.println("***FIM\n");
	}

	public static void process(List<Item> items) {
		System.out.println("processing...");

//		for (Item i : items) {
//			if (classes.get(i.getId()) == null) {
//				int reference_id = Colony.getBestMemoryId(i);
//				Integer reference = classes.get(reference_id);
//				if (reference != null) {
//					classes.put(i.getId(), reference);
//				}else{
//					reference = Engine.rand.nextInt(count_class);
//					classes.put(i.getId(), reference);
//				}
//			}
//		}

		double dintra = 0;
		int count = 0;

		for (int i = 0; i < count_class; i++) {
			List<Integer> classe = new ArrayList<Integer>();

			NavigableSet<Integer> keys = classes.navigableKeySet();
			for (Integer k : keys) {
				if (classes.get(k) == i) {
//					System.out.println("id: " + k + "\tclass: "
//							+ classes.get(k));
					classe.add(k);
				}
			}
			agrupamentos.add(classe);

			for (Integer a : classe) {
				for (Integer b : classe) {
					if (a.intValue() != b.intValue()) {
						count++;
						dintra += DistanceMatrix.matrix[a][b];
					}
				}
			}
		}
		dintra = dintra / count;
		//System.out.println("dintra: " + dintra);

		count = 0;
		double dinter = 0;
		for (int i = 0; i < agrupamentos.size(); i++) {

			for (int j = 0; j < agrupamentos.size(); j++) {
				for (Integer pivot : agrupamentos.get(i)) {
					if (i != j) {

						for (Integer target : agrupamentos.get(j)) {
							count++;
							dinter += DistanceMatrix.matrix[pivot][target];
						}
					}
				}
			}
		}
		dinter = dinter / count;
		//System.out.println("dinter: " + dinter);
		System.out.println(dintra / dinter);
	}
}
